package org.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.yulichang.base.MPJBaseServiceImpl;
import org.example.Entity.Setmeal;
import org.example.Entity.SetmealDish;
import org.example.Mapper.SetmealMapper;
import org.example.common.CustomException;
import org.example.dto.SetmealDto;
import org.example.service.SetmealDishService;
import org.example.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SetmealServiceImpl extends MPJBaseServiceImpl<SetmealMapper, Setmeal> implements SetmealService {
    @Autowired
    private SetmealDishService setmealDishService;
    @Override
    public void saveWithDishes(SetmealDto setmealDto) {
        //1.向setmeal表中添加一条setmeal
        super.save(setmealDto);
        //2.向setmeal_dish表中添加setmealDishes
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes().stream().map(item -> {
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());
        setmealDishService.saveBatch(setmealDishes);
    }

    /**
     * 删除套餐，同时删除套餐关联的菜品数据
     * @param ids
     */
    @Override
    public void removeWithDishes(List<Long> ids) {
        //1.判断是否停售,若未停售抛出异常
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Setmeal::getStatus,1)
                .in(Setmeal::getId,ids);
        int count = this.count(queryWrapper);
        if (count > 0) throw new CustomException("请先停售所选的套餐！");
        //2.删除setmeal_dish表数据
        LambdaQueryWrapper<SetmealDish> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.in(SetmealDish::getSetmealId,ids);
        setmealDishService.remove(queryWrapper1);
        //3.删除setmeal表数据
        this.removeByIds(ids);
    }
}
